package com.biostime.qdingding.modules.qd.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.biostime.qdingding.common.service.CrudService;
import com.biostime.qdingding.modules.qd.api.BasicApi;
import com.biostime.qdingding.modules.qd.api.dto.ContractDto;
import com.biostime.qdingding.modules.qd.api.dto.PersonalCenterDto;
import com.biostime.qdingding.modules.qd.dao.ContractDao;
import com.biostime.qdingding.modules.qd.dao.MemberDao;
import com.biostime.qdingding.modules.qd.dao.MemberstudentDao;
import com.biostime.qdingding.modules.qd.dao.StudentDao;
import com.biostime.qdingding.modules.qd.entity.Center;
import com.biostime.qdingding.modules.qd.entity.Contract;
import com.biostime.qdingding.modules.qd.entity.Member;
import com.biostime.qdingding.modules.qd.entity.Memberstudent;
import com.biostime.qdingding.modules.qd.entity.Privilege;
import com.biostime.qdingding.modules.qd.entity.Student;
import com.biostime.qdingding.modules.qd.entity.Transrecord;
import com.biostime.qdingding.modules.sys.entity.User;

/**
 * 会员Service
 * @author phil
 * @version 2015-11-06
 */
@Service
@Transactional(readOnly = true)
public class MemberService extends CrudService<MemberDao, Member> {
	
	@Autowired
	private MemberDao memberDao;
	@Autowired
	private ContractDao contractDao;
	@Autowired
	private StudentDao studentDao;
	@Autowired
	private MemberstudentDao memberStudentDao;
	@Autowired
	private TransrecordService transrecordService;
		
	public Member getByMobile(String mobile){
		return memberDao.getByMobile(mobile);
	}
	
	public List<Member> findAPPUser(Member member){
		return dao.findAPPUser(member);
	}
	
	@Override
	public List<Member> findList(Member entity) {
		//权限过滤
		if(entity == null){
			entity = new Member();
		}
		dataScopeFilter(entity, "dsf", "id=a.center_id", "id=a.create_by");
		
		return super.findList(entity);
	}
	
	public List<Member> findListByMobile(Member entity) {
		return dao.findListByMobile(entity);
	}
	
//	<!-- ————————————————————————————楚河汉界，APP开发，敢动？打死! ————————————————————————————————————-->
	public PersonalCenterDto apiGet(String userId){
		return memberDao.apiGet(userId);
	}
	
	public int apiUpdateDistrict(String userId, String district){
		return memberDao.apiUpdateDistrict(userId,district);
	}	
	
	public List<String> apiGetChildId(String memberId){
		return memberDao.apiGetChildId(memberId);
	}
	
	public List<String> apiGetParentId(String studentId){
		return memberDao.apiGetParentId(studentId);
	}
	
	/**
	 * 会员注册,并且创建临时合同
	 * @param member
	 * @return
	 */
	@Transactional
	public int apiInsert(Member member){	
		
		//合同
		Contract contract = new Contract();		
		
		//中心
		Center center= new Center();
		center.setId(String.valueOf(BasicApi.defaultCenterId)); 
		contract.setCenter(center);
		
		//中止特权
		contract.setAbortPriv(new Privilege());
		
		//请假特权
		contract.setLeavePriv(new Privilege());
		
		//新增学员记录
		Student student = new Student();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmSS");
		student.setCode("TP"+sdf.format(new Date()) +(new Random().nextInt(900)+100)); 
		student.setName(member.getNikename()+"宝宝");
		student.setBirthday(new Date()); 
		student.setSex(-1); 
		student.setNikename("虚拟学员"); 
		student.setCreateBy(new User("1"));
		student.setUpdateBy(new User("1"));
		student.setCreateDate(new Date());
		student.setUpdateDate(new Date());
		student.setDelFlag("0");
		student.setState(0); 
		student.setMobile(member.getMobile()); 
		student.setCenter(new Center(String.valueOf(BasicApi.defaultCenterId)));
		studentDao.insert(student);
		student.setId(student.getId());
		contract.setStudent(student); 
		
		//新增会员记录
		int i = memberDao.insert(member);
		member.setId(member.getId());   
		member.setName(member.getNikename()); 
	    contract.setMember(member); 
	    
	    //新增学员会员记录
	    Memberstudent memberStudent = new Memberstudent();
	    memberStudent.setStudentId(Integer.parseInt(student.getId()));
	    memberStudent.setMemberId(Integer.parseInt(member.getId())); 
	    memberStudentDao.insert(memberStudent);
	    
		//创建临时合同
		int contractId = newTemporaryContract(contract);		
		
		//新增收支记录
		Transrecord tr = new Transrecord();
		tr.setMemberId(Integer.parseInt(member.getId())); //会员编号
		tr.setStudentId(Integer.parseInt(student.getId())); //学员编号
		tr.setContractId(contractId); //合同编号
		tr.setCenterId(Integer.parseInt(contract.getCenter().getId()));//中心编号
		tr.setType("0");
		tr.setMoney(0.10); 
		tr.setPayType("0"); 
		tr.setDescription("临时合同"); 
		tr.setInvalid(0); 
		transrecordService.apiPay(tr); 
		
		return i;
	}
	
	public int apiUpdateNickname(String userId, String nickname){
		return memberDao.apiUpdateNickname(userId,nickname);
	}
	
	/**
	 *  新建临时合同
	 * @return
	 */
	public int newTemporaryContract(Contract contract){
		
		//合同信息
		contract.setAbort(0);
		contract.setAmount(0.1);
		contract.setAttachUrl(null);
		contract.setBroken(0);
		contract.setBrokenReason(null); 
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmSS");
		contract.setCode("TP"+sdf.format(new Date()) +(new Random().nextInt(900)+100)); 
		contract.setCreateBy(new User("1")); 
		contract.setCreateDate(new Date());
		contract.setCurrentUser(new User("1"));
		contract.setDelFlag("0");
		contract.setIsFree(0); 
		contract.setStatus(0);
		contract.setUpdateBy(new User("1")); 
		contract.setUpdateDate(new Date()); 
		contract.setValidityTime(0); 
		contract.setSignDate(new Date()); 
		contract.setType("free"); 
		
		try {
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = sdf1.parse("2100-12-25 12:10:12");
			contract.setLimitDate(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		User user = new User();
		user.setId("0");
		user.setName("admin");
		contract.setSales(user);  
		contractDao.insert(contract);
		
		return Integer.parseInt(contract.getId());
	}		
	
	/**
	 * 判断是否是会员
	 * @param student
	 * @return
	 */
	public String memberRank(Student student){
		String rank = null;
		
		//如果学生为空，则默认取studentId为0
		//通过是否存在学员，判断是否会员；前期需求
		if(student == null){
			rank = "nonMember";
			student = new Student();
			student.setId(String.valueOf(BasicApi.defaultStudentId)); 
		}else{
			if(student.getId().equals(BasicApi.defaultStudentId)){
				rank = "nonMember";
			}else{
				rank = "member";
			}
		}
		
		//通过合同类型判断会员，非会员；后期需求
		List<ContractDto> contractDtos = contractDao.apiGetContract(student.getId());
	
		if(contractDtos != null && !contractDtos.isEmpty()){
			 
		//暂时会员只存在一份有效合同，先默认取第一份
		if(contractDtos.get(0).getType() != null &&contractDtos.get(0).getType().equals("free")){
			rank = "nonMember";
		}else{
			rank = "member";
		}
		}		
		
		return rank;
	}
	
	/**
	 * 判断是否是会员
	 * @param member
	 * @version 2016-03-16
	 * @return
	 */
	public String memberRank_version2(String studentId){
		String rank = "nonMember";	 
		List<ContractDto> contractList = contractDao.apiGetContract(studentId); 
		if(contractList != null && !contractList.isEmpty()){
			if(contractList.get(0).getType() != null && !contractList.get(0).getType().equals("free")){ 
				rank = "member";
			}
			else if(contractList.get(0).getType() == null){
				rank = "member";
			}
		}
		return rank;
	}	
}
